package com.hhs.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.bean.dto.DepartUserStats;
import com.hhs.storage.dao.BaseDepartmentDao;
import com.hhs.storage.dao.BaseUserDao;
import com.hhs.storage.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-01-12
 */
@Service
@Transactional
public class BaseDepartmentServiceImpl extends ServiceImpl<BaseDepartmentDao, BaseDepartment> implements BaseDepartmentService {

    @Resource
    BaseDepartmentUserService baseDepartmentUserService;

    @Resource
    BaseUserService baseUserService;
    @Resource
    BaseRoleService baseRoleService;
    @Resource
    BaseUserDao baseUserDao;
    @Resource
    SeeDepartmentUserService seeDepartmentUserService;
    @Resource
    private HttpServletRequest request;

    @Resource
    PersonConfigService personConfigService;

    @Override
    public Map<String, Object> addOrUpdate(BaseDepartment baseDepartment) {
        //根节点部门信息
        BaseDepartment firstDepart = null;
        //如果传进来的pid为空
        if (StringUtils.isEmpty(baseDepartment.getPid())) {
            QueryWrapper ew = new QueryWrapper<BaseDepartment>();
            ew.isNull("pid");
            List<BaseDepartment> list = this.list(ew);
            if (list.size() > 0) {
                firstDepart = list.get(0);
            }
        } else {
            //pid不为空的，要设置祖先数据
            QueryWrapper ew = new QueryWrapper<BaseDepartment>();
            ew.eq("id", baseDepartment.getPid());
            List<BaseDepartment> list = this.list(ew);
            if (list.size() > 0) {
                BaseDepartment parentDepart = list.get(0);
                String prefix = parentDepart.getAncestor() == null ? "" : parentDepart.getAncestor();
                String ancestor = prefix + "," + baseDepartment.getPid();
                baseDepartment.setAncestor(ancestor);
            }
        }
        //
        if (StringUtils.isEmpty(baseDepartment.getId())) {
            //新增部门
            //pid为空，表示新增根节点部门
            if (StringUtils.isEmpty(baseDepartment.getPid()) && firstDepart != null) {
                return ResponseInfo.error("有且仅能有一个根节点");
            }
            this.save(baseDepartment);
        } else {
            //编辑部门
            if (StringUtils.isEmpty(baseDepartment.getPid()) &&
                    !baseDepartment.getId().equals(firstDepart.getId())) {
                return ResponseInfo.error("有且仅能有一个根节点");
            }
            this.updateById(baseDepartment);
        }
        return ResponseInfo.success(baseDepartment);
    }

    @Override
    public Map<String, Object> dele(String id) {
        if (StringUtils.isEmpty(id)) {
            return ResponseInfo.error("数据错误");
        }
        //部门有人员，不允许删除
        QueryWrapper ew = new QueryWrapper<BaseDepartmentUser>();
        ew.eq("depart_id", id);
        int countUser = baseDepartmentUserService.count(ew);
        if (countUser > 0) {
            return ResponseInfo.error("该部门有职员，无法删除");
        }
        //部门有下级，不允许删除
        int count = count(new QueryWrapper<BaseDepartment>().eq("pid", id));
        if (count > 0) {
            return ResponseInfo.error("该部门有下级，无法删除");
        }
        removeById(id);
        return ResponseInfo.success(null);

    }

    @Override
    public Map<String, Object> join(String userId, String departId, String seeDepartId,Integer type) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(departId)) {
            return ResponseInfo.error("数据错误");
        }
        String[] arr = departId.split(",");
        //删除旧的
        baseDepartmentUserService.remove(new QueryWrapper<BaseDepartmentUser>().eq("user_id", userId));
        //关联新的
        for (String s : arr) {
            BaseDepartmentUser temp = new BaseDepartmentUser();
            temp.setDepartId(s);
            temp.setUserId(userId);
            temp.setType(type);
            baseDepartmentUserService.save(temp);
        }
        //职员其他可见部门的配置
        //删除旧的
        seeDepartmentUserService.remove(new QueryWrapper<SeeDepartmentUser>().eq("user_id", userId));
        if(!StringUtils.isEmpty(seeDepartId)){
            String[] arr2 = seeDepartId.split(",");
            //关联新的
            for (String s : arr2) {
                SeeDepartmentUser temp = new SeeDepartmentUser();
                temp.setDepartId(s);
                temp.setUserId(userId);
                seeDepartmentUserService.save(temp);
            }
        }
        return ResponseInfo.success(null);
    }

    @Override
    public List<BaseDepartment> findByUserId(String userId) {
        return this.baseMapper.findByUserId(userId);
    }

    @Override
    public List<BaseDepartment> findSeeByUserId(String userId) {
        return this.baseMapper.findSeeByUserId(userId);
    }

    @Override
    public Map<String, Object> getUsers(InputParam inputParam) {
        if("all".equals(inputParam.getId())){
            inputParam.setId("");
        }
        //特殊处理，若部门id存在，则改成in查询
        if (StringUtils.isNotEmpty(inputParam.getId())) {
            String temp = " (";
            String[] idArr = inputParam.getId().split(",");
            List<String> idList = new ArrayList<>();
            for (int i = 0; i < idArr.length; i++) {
                idList.add("'" + idArr[i] + "'");
            }
            String idtemp = idList.stream().map(String::valueOf).collect(Collectors.joining(","));
            temp += idtemp + ") ";
            inputParam.setId(temp);
        }
        if (inputParam.getPage() == null || inputParam.getSize() == null) {
            return ResponseInfo.error("参数错误");
        }
        inputParam.setOffset((inputParam.getPage() - 1) * inputParam.getSize());

        Map<String, Object> map = new HashMap<String, Object>();
        //排除管理员
        inputParam.setIgnorUserIds(SysUtil.EXCLUDE_USERS);
        List<BaseUser> list = baseUserDao.getUsersByDepart(inputParam);
        //获取每个用户的角色名称，方便前端展示
        for (BaseUser record : list) {
            List<BaseRole> roleList = baseRoleService.getByUserId(record.getId());
            if (roleList.size() > 0) {
                String temp = "";
                for (BaseRole o : roleList) {
                    temp += o.getName() + "，";
                }
                temp = temp.substring(0, temp.length() - 1);
                record.setRoleNames(temp);
            }
            //获取每个用户的部门名称，方便前端展示
            List<BaseDepartment> departList = this.findByUserId(record.getId());
            if (departList.size() > 0) {
                String temp = "";
                for (BaseDepartment o : departList) {
                    temp += o.getName();
                    if (o.getType().equals(1)) {
                        temp += "负责人";
                    } else if (o.getType().equals(2)) {
                        temp += "职员";
                    }
                    temp += ",";
                }
                temp = temp.substring(0, temp.length() - 1);
                record.setDepartNames(temp);
            }
        }
        map.put("rows", list);
        map.put("total", baseUserDao.totalUsersByDepart(inputParam));
        map.put("code", 1);
        return map;
    }
    @Override
    public Map<String, Object> getUsersEx(InputParam inputParam) {
        //特殊处理，若部门id存在，则改成in查询
        if (StringUtils.isNotEmpty(inputParam.getId())) {
            String temp = " (";
            String[] idArr = inputParam.getId().split(",");
            List<String> idList = new ArrayList<>();
            for (int i = 0; i < idArr.length; i++) {
                idList.add("'" + idArr[i] + "'");
            }
            String idtemp = idList.stream().map(String::valueOf).collect(Collectors.joining(","));
            temp += idtemp + ") ";
            inputParam.setId(temp);
        }
        if (inputParam.getPage() == null || inputParam.getSize() == null) {
            return ResponseInfo.error("参数错误");
        }
        inputParam.setOffset((inputParam.getPage() - 1) * inputParam.getSize());

        Map<String, Object> map = new HashMap<String, Object>();
        //排除自己
        String userId = SysUtil.getLoginUserId(request);
        String[] idArr={userId};
        String[] both = (String[]) ArrayUtils.addAll(SysUtil.EXCLUDE_USERS, idArr);
        inputParam.setIgnorUserIds(both);
        List<BaseUser> list = baseUserDao.getUsersByDepart(inputParam);
        //获取每个用户的角色名称，方便前端展示
        for (BaseUser record : list) {
            List<BaseRole> roleList = baseRoleService.getByUserId(record.getId());
            if (roleList.size() > 0) {
                String temp = "";
                for (BaseRole o : roleList) {
                    temp += o.getName() + "，";
                }
                temp = temp.substring(0, temp.length() - 1);
                record.setRoleNames(temp);
            }
            //获取每个用户的部门名称，方便前端展示
            List<BaseDepartment> departList = this.findByUserId(record.getId());
            if (departList.size() > 0) {
                String temp = "";
                for (BaseDepartment o : departList) {
                    temp += o.getName();
                    if (o.getType().equals(1)) {
                        temp += "负责人";
                    } else if (o.getType().equals(2)) {
                        temp += "职员";
                    }
                    temp += ",";
                }
                temp = temp.substring(0, temp.length() - 1);
                record.setDepartNames(temp);
            }
        }
        map.put("rows", list);
        map.put("total", baseUserDao.totalUsersByDepart(inputParam));
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> isPrincipal(InputParam inputParam) throws IOException {
        QueryWrapper ew = new QueryWrapper<BaseDepartmentUser>();
        ew.eq("user_id", inputParam.getCurUserId());
        ew.eq("type", 1);
        List<BaseDepartmentUser> list = baseDepartmentUserService.list(ew);
        if (list.size() > 0) {
            Map<String, Object> resultMap = formatUserDepart(list);
            resultMap.put("code", 1);
            return resultMap;
        }
        //不返回error，防止前端提示，仅用于判断
        return ResponseInfo.success();
    }
    //根据用户-部门中间表的数据，查询所属部门以及下属部门，并封装部门id成字符串
    private Map formatUserDepart(List<BaseDepartmentUser> list){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("myDepart", null);
        resultMap.put("idsStr", null);
        //仅取部门id
        List<String> departIdList = new ArrayList<>();
        //是以下部门的负责人
        String isPrincipalStr=",";
        for (BaseDepartmentUser baseDepartmentUser : list) {
            departIdList.add(baseDepartmentUser.getDepartId());
            if(baseDepartmentUser.getType()!=null && baseDepartmentUser.getType() == 1){
                isPrincipalStr+=baseDepartmentUser.getDepartId();
            }
        }
        //去重
        departIdList = departIdList.stream().distinct().collect(Collectors.toList());
        //部门数据获取
        if (departIdList.size() > 0) {
            //用户拥有的部门以及下属部门
            List<BaseDepartment> myDepart = new ArrayList<>();
            //拼接所有的部门以及下属部门id成一个字符串
            HashSet<String> idArr = new HashSet<>();
            //所有的子部门节点
            HashSet<String> childIds = new HashSet<>();
            //数据库里的所有部门
            List<BaseDepartment> allList = getAll();
            //一个人可以有多个部门，但必须同时是负责人或者职员
            //拼接所有的部门
            for (String departId : departIdList) {
                //查询该部门以及下属部门
                List<BaseDepartment> formatList = BaseDepartment.format(allList, departId);
                for (BaseDepartment baseDepartment : formatList) {
                    //该部门id在负责人字符串里
                    if(isPrincipalStr.contains(baseDepartment.getId())){
                        baseDepartment.setPrincipal(true);
                    }
                    idArr.add(baseDepartment.getId());
                    if (baseDepartment.getChildren().size() > 0) {
                        //TODO:当前规则，若是该部门的负责人，则也是下级的负责人
                        formatIds(baseDepartment.getChildren(), idArr, childIds, isPrincipalStr,baseDepartment.isPrincipal());
                    }
                    myDepart.add(baseDepartment);
                }
            }
            //清除上下级关系错误的外层数据
            //若外层部门已经是某个的子级，则删除
            for (int i = 0; i < myDepart.size(); i++) {
                String id = myDepart.get(i).getId();
                if (childIds.contains(id)) {
                    myDepart.remove(i);
                    i--;
                }
            }
            String idsStr = idArr.stream().map(String::valueOf).collect(Collectors.joining(","));
            //TODO:部门的排序规则,利用ancestor的个数来排序
            resultMap.put("myDepart", myDepart);
            resultMap.put("idsStr", idsStr);
        }
        return resultMap;
    }
    /**
     * 获取当前登录用户的部门和下级部门信息
     *
     * @return
     */
    @Override
    public Map<String, Object> getDepartDataByLoginUser(InputParam inputParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String userId="";
        if(StringUtil.iszNull(inputParam.getUserId())){
            userId = SysUtil.getLoginUserId(request);
        }else{
            userId=inputParam.getUserId();
        }
        QueryWrapper ew = new QueryWrapper<BaseDepartmentUser>();
        ew.eq("user_id", userId);
        List<BaseDepartmentUser> list = baseDepartmentUserService.list(ew);
        if (list.size() > 0) {
            Map<String, Object> temp = formatUserDepart(list);
            resultMap.put("code", 1);
            List<BaseDepartment> allList = getAll();
            resultMap.put("allDepartments", allList);
            resultMap.put("userDepartment", temp.get("myDepart"));
//            resultMap.put("isPrincipal", temp.get("isPrincipal"));//是否部门负责人
            resultMap.put("idsStr", temp.get("idsStr"));
            return resultMap;
        }else{
            resultMap.put("code", 1);//防止前端抛异常信息
            return resultMap;
        }

    }

    /**
     * 获取指定用户所属部门所有成员与下级部门所有成员
     *
     * @return
     */
    @Override
    public List<BaseUser> getUserDepartAllUser(String userId) {
        QueryWrapper ew = new QueryWrapper<BaseDepartmentUser>();
        ew.eq("user_id", userId);
        List<BaseDepartmentUser> list = baseDepartmentUserService.list(ew);
        if (list.size() > 0) {
            Map<String, Object> temp = formatUserDepart(list);
            String idsStr =  temp.get("idsStr").toString();
            String[] idArr = idsStr.split(",");
            List<String> idList = new ArrayList<>();
            for (String s : idArr) {
                idList.add("'" + s + "'");
            }
            String departIds = idList.stream().map(String::valueOf).collect(Collectors.joining(","));
            QueryWrapper<BaseUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.inSql("id_", "SELECT user_id FROM base_department_user WHERE depart_id IN(" + departIds + ")");
            return baseUserDao.selectList(userQueryWrapper);
        }else{
            //暂未分配部
            return new ArrayList<BaseUser>();
        }

    }
    //将所有部门id与子部门id 拼接成一个字符串
    //isPrincipal 上级部门是否是负责人的标识，若上级是负责人，则所有下级都是负责人
    private void formatIds(List<BaseDepartment> list, HashSet<String> idArr,
                           HashSet<String> childIds,String isPrincipalStr,
                           boolean isPrincipal) {
        for (BaseDepartment baseDepartment : list) {
            //若上级是负责人
            if(isPrincipal){
                baseDepartment.setPrincipal(true);
            }else {
                //若是该部门的负责人
                if (isPrincipalStr.contains(baseDepartment.getId())) {
                    baseDepartment.setPrincipal(true);
                    isPrincipal = true;
                }
            }
            idArr.add(baseDepartment.getId());
            childIds.add(baseDepartment.getId());
            if (baseDepartment.getChildren().size() > 0) {
                formatIds(baseDepartment.getChildren(), idArr,childIds,isPrincipalStr,isPrincipal);
            }
        }
    }

    @Override
    public List<BaseDepartment> getAll() {
        List<BaseDepartment> list = list(new QueryWrapper<BaseDepartment>());
        return list;
    }

    /**
     * 查询用户所在部门负责人
     *2023-04-21修改 还要查上上级部门领导
     * @return
     */
    @Override
    public Map<String, Object> getDepartHeader() {
        String userId = SysUtil.getLoginUserId(request);
        //查询用户所有部门信息
        QueryWrapper qw = new QueryWrapper<BaseDepartment>();
        qw.inSql("id", "SELECT depart_id FROM base_department_user WHERE user_id='" + userId + "' ");
        qw.orderByAsc("ancestor");
        List<BaseDepartment> departmentList=this.list(qw);
        //查询所有部门及上级部门负责人
        List<BaseUser> headers=new ArrayList<>();
        //查询所有部门
        for (int i = 0; i <departmentList.size() ; i++) {
            BaseDepartment depart=departmentList.get(i);
            String pid=depart.getPid();//上级部门id
            if (StringUtils.isNotEmpty(pid)){//有上级部门，查询上级部门负责人信息
                BaseDepartment parentDepart=this.getById(pid);
                qw=new QueryWrapper<BaseUser>();
                qw.ne("id_",userId);//忽略当前用户
                qw.orderByAsc("order_num");
                qw.inSql("id_","SELECT DISTINCT user_id FROM base_department_user where type=1  and  depart_id='"+parentDepart.getId()+"'");
                List<BaseUser> users=baseUserDao.selectList(qw);
                for (int j = 0; j <users.size() ; j++) {
                    users.get(j).setDepartment(parentDepart);
                }
                headers.addAll(users);
            }
            //查询部门负责人
            qw=new QueryWrapper<BaseUser>();
            qw.ne("id_",userId);//忽略当前用户
            qw.orderByAsc("order_num");
            qw.inSql("id_","SELECT DISTINCT user_id FROM base_department_user where TYPE=1  and  depart_id='"+depart.getId()+"'");
            List<BaseUser> users=baseUserDao.selectList(qw);
            for (int j = 0; j <users.size() ; j++) {
                users.get(j).setDepartment(depart);
            }
            headers.addAll(users);
        }
        return ResponseInfo.success(headers);
    }

    /**
     * 获取所有子部门
     *
     * @param pid
     * @return
     */
    @Override
    public List<BaseDepartment> getChildDeparts(String pid) {
        List<BaseDepartment> list = this.baseMapper.getChildDeparts(pid);
        return list;
    }

    /**
     * 获取用户所有部门与子部门
     *
     * @return
     */
    @Override
    public Map<String, Object> getUserDepartInfo() {
        String userId = SysUtil.getLoginUserId(request);
        QueryWrapper ew = new QueryWrapper<BaseDepartmentUser>();
        ew.eq("user_id", userId);
        List<BaseDepartmentUser> list = baseDepartmentUserService.list(ew);
        if (list.size() == 0) {//暂未分配部
            return ResponseInfo.success(list);
        }
        Set<String> childIds = new HashSet<>();
        List<BaseDepartment> userDepartList=new ArrayList<>();//用户的部门列表
        //查询部门与子部门
        for (int i = 0; i < list.size(); i++) {
            String pid = list.get(i).getDepartId();
            BaseDepartment department = getById(pid);
            List<BaseDepartment> childs = getChildDeparts(pid);
            department.setChildren(BaseDepartment.getChild(pid,childs));
            //记录所有子节点id
            for (int j = 0; j < childs.size(); j++) {
                childIds.add(childs.get(j).getId());
            }
            userDepartList.add(department);
        }
       //移除所有已在子部门中的父级的部门
        //2.使用for循环删除list中的某一个元素
        for(int i=0;i<userDepartList.size();i++){
            String id=userDepartList.get(i).getId();
            if (childIds.contains(id)){
                userDepartList.remove(i);
                i--;
            }
        }
        return ResponseInfo.success(userDepartList);
    }

    @Override
    public Map<String, Object> sumUsers(Integer type) {
        InputParam inputParam = new InputParam();
        if(type!=null && type==1){
            //排除管理员 以及 用户账号停用的数据
            List<BaseUser> tempList = baseUserService.getBaseMapper().selectList(
                    new QueryWrapper<BaseUser>().eq("status_", 0));
            if(tempList!=null && tempList.size()>0){
                String userId = SysUtil.getLoginUserId(request);
                String[] idArr= new String[tempList.size()];
                for (int i=0;i<tempList.size();i++) {
                    idArr[i]=tempList.get(i).getId();
                }
                String[] both = (String[]) ArrayUtils.addAll(SysUtil.EXCLUDE_USERS, idArr);
                inputParam.setIgnorUserIds(both);
            }else{
                inputParam.setIgnorUserIds(SysUtil.EXCLUDE_USERS);
            }
        }else{
            //排除管理员
            inputParam.setIgnorUserIds(SysUtil.EXCLUDE_USERS);
        }
        //查询出有职员的各个部门
        List<DepartUserStats> list = this.baseMapper.sumUsers(inputParam);
        //查出所有部门，不管部门是否有职员
        List<BaseDepartment> all = this.getAll();

        List<DepartUserStats> allList = new ArrayList<>();
        for (BaseDepartment baseDepartment : all) {
            DepartUserStats ds = new DepartUserStats();
            ds.setId(baseDepartment.getId());
            for (DepartUserStats stats2 : list) {
                if(stats2.getId().equals(baseDepartment.getId())){
                    ds.setCurTotal(stats2.getCurTotal());
                    ds.setAncestor(stats2.getAncestor());
                    ds.setTotal(stats2.getTotal());
                }
            }
            allList.add(ds);
        }
        //计算各个部门的总职员数
        for (DepartUserStats stats : allList) {
            for (DepartUserStats stats2 : list) {
                if(!StringUtils.isEmpty(stats2.getAncestor())
                        && stats2.getAncestor().indexOf(stats.getId())>0){
                    Integer temp = stats.getTotal()+stats2.getCurTotal();
                    stats.setTotal(temp);
                }
            }
        }
        return ResponseInfo.success(allList);
    }

    @Override
    public Map<String, Object> indexDepart() {
        //查询该用户所属部门以及首页可见的其他部门  这个接口仅用于首页
        //
        String userId = SysUtil.getLoginUserId(request);
        if( StringUtils.isEmpty(userId)){
            return ResponseInfo.error("数据错误");
        }
        //所属部门表
        QueryWrapper ew = new QueryWrapper<BaseDepartmentUser>();
        ew.eq("user_id", userId);
        List<BaseDepartmentUser> list = baseDepartmentUserService.list(ew);

        //可见部门表
        QueryWrapper ew2 = new QueryWrapper<SeeDepartmentUser>();
        ew2.eq("user_id", userId);

        List<SeeDepartmentUser> list2 = seeDepartmentUserService.list(ew2);
        for (SeeDepartmentUser seeDepartmentUser : list2) {
            BaseDepartmentUser temp = new BaseDepartmentUser();
            temp.setDepartId(seeDepartmentUser.getDepartId());
            list.add(temp);
        }
        //数据库里的所有部门
        List<BaseDepartment> allList = getAll();
        if (list.size() > 0) {
            Map<String, Object> resultMap = formatUserDepart(list);
            List<BaseDepartment> firstList= (List<BaseDepartment>)resultMap.get("myDepart");
            //外层的部门再次查出它的上级部门
            for (BaseDepartment curDepart : firstList) {
                if(!StringUtils.isEmpty(curDepart.getPid())){
                    for (BaseDepartment temp : allList) {
                        if(curDepart.getPid().equals(temp.getId())){
                            curDepart.setParent(temp);
                        }
                        continue;
                    }
                }
            }
            //排序
            Collections.sort(firstList);
            for (BaseDepartment bd :
                    firstList) {
                //处理部门人数

            }
            resultMap.put("myDepart",firstList);
            resultMap.put("code", 1);
            return resultMap;
        }
        return ResponseInfo.error("该用户未有部门，请联系管理员配置");
    }

    @Override
    public Map<String, Object> principalOpera(String userId) {
        //curUserId当前请求发起人 ； userId 查看人
        String curUserId = SysUtil.getLoginUserId(request);
        if( StringUtils.isEmpty(userId) ||
                StringUtils.isEmpty(curUserId)){
            return ResponseInfo.error("数据错误");
        }
        //是自己，可以操作
        if(curUserId.equals(userId)){
             return ResponseInfo.success(true);
        }
        //被查询用户的部门等级
        List<BaseDepartment> list = findByUserId(userId);
        int level=100;
        for (BaseDepartment depart : list) {
            //是负责人
            if(depart.getType().equals(1) && depart.getLevel()<level){
                level=depart.getLevel();
            }
        }
        //自己的部门等级
        List<BaseDepartment> curlist = findByUserId(curUserId);
        int curLevel=100;
        for (BaseDepartment depart : curlist) {
            //是负责人
            if(depart.getType().equals(1) && depart.getLevel()<curLevel){
                curLevel=depart.getLevel();
            }
        }
        boolean isBelong= isBelongToSub(curUserId,userId);
        //若负责人的部门等级高于被查询人，并且被查询人是负责人的下属
        if(curLevel<level && isBelong) {
            return ResponseInfo.success(true);
        }else{
            return ResponseInfo.success(false);
        }

    }
    /**
     * 根据当前用户的部门关系类型获取部门数据
     * @param type leader=查询上级 user=查询下级
     * @return
     */
    @Override
    public Map<String, Object> getDepartByRelateType(String type) {
        if (SysUtil.RELATE_TYPE_MAP.get(type)==null){
            return ResponseInfo.error("错误参数");
        }
        //查询下级部门
        if (type.equals("user")){
            return this.getUserDepartInfo();
        }
        String userId=SysUtil.getLoginUserId(request);
        QueryWrapper<BaseDepartment> qw=new QueryWrapper<>();
        //查询用户所有部门
        qw.inSql("id","SELECT depart_id FROM base_department_user WHERE user_id='"+userId+"'");
        List<BaseDepartment> list=this.list(qw);
        //查询上级部门
        if (type.equals("leader")){
            Set<String> ancestorIds=new HashSet<>();
            for (int i = 0; i <list.size() ; i++) {
                if (list.get(i).getAncestor()!=null){
                    //获取所有上级id，并去重
                    ancestorIds.addAll(Arrays.asList(list.get(i).getAncestor().split(",")));
                }

                //添加当前部门id
                ancestorIds.add(list.get(i).getId());
            }
            //查询相关部门信息
            qw=new QueryWrapper<>();
            qw.in("id",ancestorIds.toArray());
            List<BaseDepartment> resultList=this.list(qw);
            Set<String> childIdSet=new HashSet<>();
            //给父级添加子集
            for (int i = 0; i <resultList.size() ; i++) {
                BaseDepartment p=resultList.get(i);
                for (int j = 0; j < resultList.size() ; j++) {
                    BaseDepartment c=resultList.get(j);
                    if(p.getId().equals(c.getPid())){
                        if (p.getChildren()==null){
                            p.setChildren(new ArrayList<BaseDepartment>());
                        }
                        p.getChildren().add(c);
                        childIdSet.add(c.getId());
                    }
                }
            }
            //移除子集
            for (int i = 0; i <resultList.size() ; i++) {
                BaseDepartment temp=resultList.get(i);
                if (childIdSet.contains(temp.getId())){
                    resultList.remove(temp);
                    i--;
                }
            }
            return ResponseInfo.success(resultList);
        }
        return ResponseInfo.success(new ArrayList<>());
    }
    /**
     * 根据关系类型获取部门用户数据
     * @param type  leader=查询负责人 user=查询职员
     * @param departIds
     * @return
     */
    @Override
    public Map<String, Object> getDepartUserDataByRelateType(String type, String departIds) {
        if (SysUtil.RELATE_TYPE_MAP.get(type)==null){
            return ResponseInfo.error("错误参数");
        }
        //将id转换成sql的in条件
        String[] idArr=departIds.split(",");
        String temp = " (";
        List<String> idList = new ArrayList<>();
        for (int i = 0; i < idArr.length; i++) {
            idList.add("'" + idArr[i] + "'");
        }
        String idtemp = idList.stream().map(String::valueOf).collect(Collectors.joining(","));
        temp += idtemp + ") ";
        QueryWrapper<BaseUser> qw=new QueryWrapper<>();
        //查询职员
        if (type.equals("user")){
            qw.inSql("id_","SELECT user_id FROM base_department_user WHERE TYPE=2 AND depart_id IN "+temp);
        }
        //查询负责人
        if (type.equals("leader")){
            qw.inSql("id_","SELECT user_id FROM base_department_user WHERE TYPE=1 AND depart_id IN "+temp);
        }
        qw.orderByAsc("order_num");//排序号升序
        return ResponseInfo.success(baseUserDao.selectList(qw));
    }
    /**
     * 获取所有部门负责人
     * @return
     */
    @Override
    public Map<String, Object> getAllHeaders() {
        QueryWrapper<BaseUser> queryWrapper=new QueryWrapper<>();
        //查询所有部门负责人id
        queryWrapper.inSql("id_","SELECT user_id FROM base_department_user WHERE TYPE=1");
        queryWrapper.orderByAsc("order_num");
        return ResponseInfo.success(baseUserDao.selectList(queryWrapper));
    }

    @Override
    public Page<BaseUser> getAllHeaders(InputParam inputParam) {
        QueryWrapper<BaseUser> queryWrapper=new QueryWrapper<>();
        //查询所有部门负责人id
        queryWrapper.inSql("id_","SELECT user_id FROM base_department_user WHERE TYPE=1");
        //除去管理员
        queryWrapper.ne("id_",2);
        queryWrapper.orderByAsc("order_num");
        Page<BaseUser> page = baseUserService.page(new Page<BaseUser>(inputParam.getPage(),inputParam.getSize()),queryWrapper);
        return page;
    }

    /**
     * 获取专属业务部门
     * @return
     */
    @Override
    public Map<String, Object> getBusinessSiteDepart() {
        //读取数据库的配置
        PersonConfig business_stat = personConfigService.getByType("business_stat", null);
        //字符串转json数组
        Type listType = new TypeReference<List<BaseDepartment>>() {}.getType();
        List<BaseDepartment> list = JSON.parseObject(business_stat.getData(), listType);
        return ResponseInfo.success(list);
    }

    /**
     * 获取用户的上级部门和自身部门
     * @param userId
     * @return
     */
    @Override
    public Map<String,Object> getParentDepartsByUserId(String userId) {
        Map<String,Object> map=new HashMap<>();
        QueryWrapper<BaseDepartment> qw=new QueryWrapper<>();
        //查询用户所有部门
        qw.inSql("id","SELECT depart_id FROM base_department_user WHERE user_id='"+userId+"'");
        List<BaseDepartment> myDepartList=this.list(qw);
        map.put("myDepartList",myDepartList);
        //获取所有上级id
        Set<String> parentDepartIds=new HashSet<>();
        for (int i=0;i<myDepartList.size();i++){
            BaseDepartment temp=myDepartList.get(i);
            String ancestor=temp.getAncestor();
            if (StringUtils.isNotEmpty(ancestor)){
                String[] ids=ancestor.split(",");
                parentDepartIds.addAll(Arrays.asList(ids));
            }
        }
        List<BaseDepartment> parentDepartList=new ArrayList<>();
        if(parentDepartIds.size()>0){
            qw=new QueryWrapper<>();
            qw.in("id",parentDepartIds.toArray());
            parentDepartList=this.list(qw);
        }
        map.put("parentDepartList",parentDepartList);
        return map;
    }

    //查询该员工是否是我的下属
    private boolean isBelongToSub(String curUserId,String userId) {
        QueryWrapper ew = new QueryWrapper<BaseDepartmentUser>();
        ew.eq("user_id", curUserId);
        ew.eq("type", 1);
        //查询出我负责的部门
        List<BaseDepartmentUser> list = baseDepartmentUserService.list(ew);
        if (list.size() > 0) {
            Map<String, Object> temp = formatUserDepart(list);
            String idsStr =  temp.get("idsStr").toString();
            String[] idArr = idsStr.split(",");
            List<String> idList = new ArrayList<>();
            //封装我的部门以及所有下属部门的id
            for (String s : idArr) {
                idList.add("'" + s + "'");
            }
            String departIds = idList.stream().map(String::valueOf).collect(Collectors.joining(","));
            QueryWrapper<BaseUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.inSql("id_", "SELECT user_id FROM base_department_user WHERE user_id='"+userId+"' and depart_id IN(" + departIds + ")");
            List<BaseUser> resList = baseUserDao.selectList(userQueryWrapper);
            if(resList.size()>0){
                return true;
            }else{
                return false;
            }
        }else{
            //暂未分配部
            return false;
        }

    }

}
